<?php
// +----------------------------------------------------------------------
// | PHP [ JUST YOU ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2017 http://www.jyphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: FlyingPig <flyingpigfp@163.com>
// +----------------------------------------------------------------------

namespace App\Logic;


use App\Common\Logger;
use App\Common\Tool;
use App\Exceptions\ApiException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class WeChatWithholdLogic extends Logic
{

    //签约的回调地址
    protected $notifyUrl = 'http://test.heroscocks.com/EntrustWebCallback';

    /**
     * @param $ua
     * @param $uid
     * @return string
     * @throws ApiException
     */
    public function entrustWebLogic($ua, $uid)
    {
        //查询用户 签约没有
        $wx_withhold_status = DB::table('t_player_info')
            ->where('uid', $uid)
            ->where('wx_contract_expired_time', '>', date('Y-m-d H:i:s'))
            ->value('wx_withhold_status');
        if ($wx_withhold_status == 1) {
            throw new ApiException('已经签约微信免密支付');
        }

        $request         = [
            'appid' => config('wechatpay.appid'),
            'mch_id' => config('wechatpay.mch_id'),
            'plan_id' => '',
            'contract_code' => Str::random(32),
            'request_serial' => $this->requestSerial($uid),
            'contract_display_account' => '代扣名称',
            'notify_url' => $this->notifyUrl($ua),
            'version' => '1.0',
            'timestamp' => time()
        ];
        $request['sign'] = WXOrderLogic::instance()->getSign($request, config('wechatpay.key'));
        return 'https://api.mch.weixin.qq.com/papay/entrustweb?' . http_build_query($request);
    }


    public function papPayApplyLogic()
    {
        //找出快要快要过期的人，一次性最大处理20个人
        $uid = DB::table('t_vip_info')
            ->where('expire_time', '>=', date('Y-m-d', strtotime('+ 2 day')))
            ->orderBy('expire_time', 'asc')->limit(20)
            ->pluck('uid');
        if (!empty($uid)) {
            //筛选出能够扣费的用户
            $user_object = DB::table('t_player_info')
                ->whereIn('id', $uid)
                ->where('status', 0)
                ->where('wx_withhold_status', 1)
                ->where('wx_contract_expired_time', '>', date('Y-m-d H:i:s'))
                ->get(['wx_contract_id', 'uid']);
        }
        if (!empty($user_object)) {
            foreach ($user_object as $value) {
                $goods_info      = $this->goodVipInfo($value->uid);
                $out_trade_no    = WXOrderLogic::instance()->createOrderId(32);
                $request         = [
                    'appid' => config('wechatpay.appid'),
                    'mch_id' => config('wechatpay.mch_id'),
                    'nonce_str' => Str::random(32),
                    'body' => '测试会员权益代扣',
                    'out_trade_no' => $out_trade_no,
                    'total_fee' => $goods_info->price * 100,
                    'spbill_create_ip' => $_SERVER['SERVER_ADDR'],
                    'notify_url' => env('WX_PAY_CALLBACK'),
                    'trade_type' => 'PAP',
                    'contract_id' => $value->wx_contract_id
                ];
                $request['sign'] = WXOrderLogic::instance()->getSign($request, config('wechatpay.key'));

                $response = WXOrderLogic::instance()->curlPost('https://api.mch.weixin.qq.com/pay/pappayapply', WXOrderLogic::instance()->arrayToXml($request));
                Logger::instance()->info('微信请求免密扣款受理响应(不代表扣款成功)', "\n" . $response . "\n\n");
                $response = Tool::xmlToArray($response);
                if ($response['return_code'] == 'SUCCESS') {
                    //创建订单信息
                    Tool::createPayInfo($out_trade_no, $goods_info->price, $uid, 5, 2, $goods_info->id);
                }
            }
        }
    }


    public function deleteContractLogic($uid)
    {
        $wx_contract_id = DB::table('t_player_info')->where('id', $uid)->where('wx_contract_expired_time', '>', time())->value('wx_contract_id');
        if (empty($wx_contract_id)) {
            throw new ApiException('签约已经失效,无需申请解约');
        }
        $request         = [
            'appid' => config('wechatpay.appid'),
            'mch_id' => config('wechatpay.mch_id'),
            'version' => 1.0,
            'contract_termination_remark' => '解除个人微信免密支付',
            'contract_id' => $wx_contract_id
        ];
        $request['sign'] = WXOrderLogic::instance()->getSign($request, config('wechatpay.key'));

        $response = WXOrderLogic::instance()->curlPost('https://api.mch.weixin.qq.com/pay/deletecontract', WXOrderLogic::instance()->arrayToXml($request));
        Logger::instance()->info('微信请求解约响应', "\n" . $response . "\n\n");
        $response = Tool::xmlToArray($response);
        if ($response['return_code'] == 'SUCCESS') {
            DB::table('t_player_info')->where('id', $uid)->update(['wx_contract_expired_time' => '', 'wx_withhold_status' => 0, 'wx_contract_id' => '']);
        }
    }


    private function requestSerial($uid)
    {
        return (int)(microtime(true) * 10000 . mt_rand(1000, 9999) . $uid);
    }

    //返回签约后的回调地址
    private function notifyUrl($ua)
    {
        if ($ua == 'iphone') {
            return urlencode(urlencode($this->notifyUrl));
        }
        return urlencode($this->notifyUrl);
    }

    /**
     * @param $uid
     */
    private function goodVipInfo($uid)
    {
        $object = DB::table('t_vip_conf')->where('id', function ($query) use ($uid) {
            $query->from('t_vip_info')->where('uid', $uid)->select(['vip_conf_id']);
        })->where('status', 1)->first(['name', 'price', 'id']);
        if (empty($object)) {
            Logger::instance()->error('微信自动续费出错','用户ID'.$uid.'将要续费的VIP商品不存在');
        }

    }


}